<template>
  <div class="diary">
    <yk-space dir="vertical" size="xl" style="width: 100%; padding-bottom: 24px;">
      <diaryItem v-for="item in diaryList" :key="item.id" :data="item" @delete="deleteDiary"
        :serchTerm="props.serchTerm"></diaryItem>
    </yk-space>
    <div class="pagination" v-show="count / props.pageSize > 1">
      <yk-pagination size="m" :total="count" @change="changePage" :default-page-size="props.pageSize" />
    </div>
    <div class="empty" v-show="count === 0">
      <yk-empty description="瞅啥呢，没数据" type="secondary"></yk-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance, watch } from 'vue';
import type { DiaryData } from '@/utils/interface';
import diaryItem from './diaryItem.vue';
import { useCode } from '@/hooks/code';
import { useUserStore } from '@/stores/user';
import { diaryAPI, deleteDiaryAPI } from '@/api';

const proxy: any = getCurrentInstance()?.proxy
const userStore = useUserStore()
const { tackleCode } = useCode()

type DiaryProps = {
  pageSize: number;
  serchTerm?: string;
  newDiary?: DiaryData
}

const props = withDefaults(defineProps<DiaryProps>(), {
  pageSize: 3,
})

const request = {
  token: userStore.token,//用户token
  pageSize: props.pageSize,//单页条数；
  nowPage: 1,//当前页
  serchTerm: props.serchTerm,//搜索词条
  count: true
}

// 获取日记
// 日记
const diaryList = ref<DiaryData[]>([]);

// 日记总数
const count = ref<number>(0);

const getData = async (e: boolean) => {
  request.count = e
  const res: any = await diaryAPI(request);
  if (tackleCode(res.code)) {
    if (e) {
      count.value = res.data.count;
    }
    diaryList.value = res.data.list
  }




}
// 删除日记
const deleteDiary = async (e: number) => {

  const request = {
    token: userStore.token,
    diaryId: e
  }
  const res: any = await deleteDiaryAPI(request);
  if (tackleCode(res.code)) {
    diaryList.value = diaryList.value.filter(item => item.id !== e)
    proxy.$message({ type: 'primary', message: '删除成功' })
  }
}



// 分页查询
const changePage = (e: number) => {
  request.nowPage = e
  getData(false)
}

watch(
  () => props.newDiary,
  (e: any) => {
    if (e) {
      diaryList.value.unshift(e);
    }
  }
)

watch(
  () => props.serchTerm,
  (e) => {
    request.serchTerm = e
    request.nowPage = 1
    getData(true)
  }
)

onMounted(() => {
  getData(true);


})
</script>

<style scoped lang="less">
.diary {
  width: 100%;

  .pagination {
    padding: @space-s 0 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
  }

  .empty {
    width: 100%;
    height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
